package netty.test13GroupChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class GroupChatServer {
    public GroupChatServer(int port) {
        this.port = port;
    }

    private int port;

    /**
     * 处理客户端请求
     */
    public void run() throws InterruptedException {
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        ServerBootstrap b=new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //获取pipleLine
                        ChannelPipeline pipeline = ch.pipeline();
                        //向pipleLine里加入一个解码器
                        pipeline.addLast("decoder",new StringDecoder());
                        // 向pipleLine 里加入 解码器
                        pipeline.addLast("encoder",new StringEncoder());
                        //向piple 里加入自己的业务处理handler
                        pipeline.addLast(new GroupChatServerHandler());

                    }
                });
        System.out.println("netty 服务器启动port="+port);
        ChannelFuture sync = b.bind(port).sync();
        //监听关闭
        sync.channel().closeFuture().sync();

    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(7000).run();
    }
}
